package com.houseliker.fragment.calculate;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.formatter.WanFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.houseliker.R;
import com.houseliker.activity.calculate.LoanDetailActivity;
import com.houseliker.activity.calculate.PieChartFragment;
import com.houseliker.activity.calculate.SelectRateActivity;
import com.houseliker.fragment.BaseFragment;
import com.houseliker.utils.IntentUtils;
import com.houseliker.utils.StringUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;

/**
 * 公积金贷款计算器
 * Created by sunrx on 2015/12/7.
 */
public class GongJiJinFragment extends BaseFragment implements OnChartValueSelectedListener {
    private View mView;
    private ScrollView scrollview;
    private PieChart pie_chart;
    private LinearLayout ll_detail;
    private TextView tv_totalprice;
    private TextView tv_benxi;
    private TextView tv_benjin;
    private EditText et_total;
    private TextView tv_calculate;
    private SeekBar seekBar_big;
    private SeekBar seekBar_normal;
    private TextView tv_rate;
    private RelativeLayout rl_rate;

    //贷款月数
    private int monthCount;
    //贷款金额
    private double loanAmount;
    //月利率
    private double monthlyRate;
    //月均贷款
    private double monthlyLoan;
    //月本息集合
    private double[] monthlyPrincipalInterests;
    //总利息
    private double interestAmount;
    //还款总额
    private double repaymentAmount;
    //贷款类型：等额本息(0)/等额本金(1)
    private int type;
    //默认贷款总额：50万
    private double defaultLoanAmount = 0;

    private DecimalFormat df = new DecimalFormat("#.##");
    private DecimalFormat df_rate = new DecimalFormat("#.####");

    private View.OnClickListener onClicker = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent;
            switch (v.getId()) {
                case R.id.ll_detail:
                    //贷款详情
                    if (repaymentAmount > 0) {
                        intent = new Intent(mContext, LoanDetailActivity.class);
                        intent.putExtra("loanAmount", loanAmount);
                        intent.putExtra("interestAmount", interestAmount);
                        intent.putExtra("monthCount", monthCount);
                        intent.putExtra("monthlyPrincipalInterests", monthlyPrincipalInterests);
                        intent.putExtra("monthlyRate", monthlyRate);
                        intent.putExtra("type", type);
                        startActivity(intent);
                    }
                    break;
                case R.id.tv_benxi:
                    type = 0;
                    tv_benxi.setBackgroundResource(R.color.greenAD);
                    tv_benjin.setBackgroundResource(R.color.grayBF);
                    if (!StringUtils.isNullOrEmpty(et_total.getText().toString())
                            && !"0".equals(et_total.getText().toString())) {
                        calculate();
                    } else if (loanAmount > 0) {
                        et_total.setText("" + df.format(loanAmount / 10000));
                        calculate();
                    }
                    PieChartFragment.gjjType = type;
                    break;
                case R.id.tv_benjin:
                    type = 1;
                    tv_benxi.setBackgroundResource(R.color.grayBF);
                    tv_benjin.setBackgroundResource(R.color.greenAD);
                    if (!StringUtils.isNullOrEmpty(et_total.getText().toString())
                            && !"0".equals(et_total.getText().toString())) {
                        calculate();
                    } else if (loanAmount > 0) {
                        et_total.setText("" + df.format(loanAmount / 10000));
                        calculate();
                    }
                    PieChartFragment.gjjType = type;
                    break;
                case R.id.tv_calculate:
                    //贷款总额
                    IntentUtils.hideSoftKeyBoard(mContext);
                    loanAmount = StringUtils.canParseDouble(et_total.getText().toString()) ? Double.parseDouble(et_total.getText().toString()) * 10000 : defaultLoanAmount;
                    PieChartFragment.gjjLoanAmount = loanAmount;
                    if (PieChartFragment.syLoanAmount == 0) {
                        PieChartFragment.syLoanAmount = loanAmount;
                    }
                    calculate();
                    break;
                case R.id.rl_rate:
                    intent = new Intent(mContext, SelectRateActivity.class);
                    intent.putExtra("from", "gjj");
                    intent.putExtra("years", seekBar_normal.getProgress());
                    startActivityForResult(intent, 1);
                    break;
                default:
                    break;
            }
        }
    };
    private SeekBar.OnSeekBarChangeListener onSeekBarChanger = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            seekBar.setThumb(getThumbDrawable(progress));
            seekBar_big.setProgress(progress);
            seekBar_big.setThumb(getThumbBigDrawable(progress));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            seekBar_normal.setVisibility(View.INVISIBLE);
            seekBar_big.setVisibility(View.VISIBLE);
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            seekBar_normal.setVisibility(View.VISIBLE);
            seekBar_big.setVisibility(View.GONE);
            if (seekBar.getProgress() > 30) {
                seekBar.setProgress(30);
            }
            if (seekBar.getProgress() < 1) {
                seekBar.setProgress(1);
            }
            PieChartFragment.GJJ_MONTHCOUNT = monthCount = seekBar.getProgress() * 12;
            if (monthCount <= 60) {
                monthlyRate = PieChartFragment.GJJ_RATE_1_5;
            } else {
                monthlyRate = PieChartFragment.GJJ_RATE_5;
            }
            tv_rate.setText(df_rate.format(monthlyRate * 12 * 100) + "%");
            if (!StringUtils.isNullOrEmpty(et_total.getText().toString())
                    && !"0".equals(et_total.getText().toString())) {
                calculate();
            } else if (loanAmount > 0) {
                et_total.setText("" + df.format(loanAmount / 10000));
                calculate();
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = setView(inflater, R.layout.my_gongjijin, TYPE_NORMAL);

        initViews();

        registListener();

        fillDatas();

        return mView;
    }

    private void initViews() {
        scrollview = (ScrollView) mView.findViewById(R.id.gjj_scrollview);
        pie_chart = (PieChart) mView.findViewById(R.id.pie_chart);
        ll_detail = (LinearLayout) mView.findViewById(R.id.ll_detail);
        tv_totalprice = (TextView) mView.findViewById(R.id.tv_totalprice);
        tv_benxi = (TextView) mView.findViewById(R.id.tv_benxi);
        tv_benjin = (TextView) mView.findViewById(R.id.tv_benjin);
        et_total = (EditText) mView.findViewById(R.id.et_total);
        tv_calculate = (TextView) mView.findViewById(R.id.tv_calculate);
        seekBar_big = (SeekBar) mView.findViewById(R.id.seekBar_big);
        seekBar_normal = (SeekBar) mView.findViewById(R.id.seekBar_normal);
        tv_rate = (TextView) mView.findViewById(R.id.tv_rate);
        rl_rate = (RelativeLayout) mView.findViewById(R.id.rl_rate);
    }

    private void registListener() {
        ll_detail.setOnClickListener(onClicker);
        tv_benxi.setOnClickListener(onClicker);
        tv_benjin.setOnClickListener(onClicker);
        tv_calculate.setOnClickListener(onClicker);
        seekBar_big.setOnSeekBarChangeListener(onSeekBarChanger);
        seekBar_normal.setOnSeekBarChangeListener(onSeekBarChanger);
        rl_rate.setOnClickListener(onClicker);
    }

    public void fillDatas() {
        initDefaultValues(PieChartFragment.gjjLoanAmount, PieChartFragment.gjjType);

        initPieChart();
    }

    private Drawable getThumbDrawable(int progress) {
        Bitmap bg = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_seeker);
        //
        Bitmap bitmap = Bitmap.createBitmap(bg.getWidth(), bg.getHeight(), Bitmap.Config.ARGB_8888);
        //
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setTextAlign(Paint.Align.CENTER);
        Rect rect = new Rect(0, 0, bg.getWidth(), bg.getHeight());
        canvas.drawBitmap(bg, rect, rect, paint);
        paint.setTextSize(StringUtils.dip2px(14));
        paint.setColor(Color.WHITE);
        canvas.drawText("" + progress, bg.getWidth() / 2, bg.getHeight() / 2 + StringUtils.dip2px(2), paint);

        Drawable drawable = new BitmapDrawable(getResources(), bitmap);
        return drawable;
    }

    private Drawable getThumbBigDrawable(int progress) {
        Bitmap bg = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_seeker_big);
        //
        Bitmap bitmap = Bitmap.createBitmap(bg.getWidth(), bg.getHeight(), Bitmap.Config.ARGB_8888);
        //
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setTextAlign(Paint.Align.CENTER);
        Rect rect = new Rect(0, 0, bg.getWidth(), bg.getHeight());
        canvas.drawBitmap(bg, rect, rect, paint);
        paint.setTextSize(StringUtils.dip2px(20));
        paint.setColor(Color.WHITE);
        canvas.drawText("" + progress, bg.getWidth() / 2, bg.getHeight() / 2 + StringUtils.dip2px(2), paint);

        Drawable drawable = new BitmapDrawable(getResources(), bitmap);
        return drawable;
    }

    private void initDefaultValues(double amount, int type) {
        //贷款总额(默认值)
        loanAmount = amount;
        if (loanAmount == 0) {
            et_total.setText("");
        } else {
            et_total.setText("" + df.format(loanAmount / 10000));
        }
        //贷款类型:等额本息(0)/等额本金(1)
        if (type == 0) {
            this.type = 0;
            tv_benxi.setBackgroundResource(R.color.greenAD);
            tv_benjin.setBackgroundResource(R.color.grayBF);
        } else {
            this.type = 1;
            tv_benxi.setBackgroundResource(R.color.grayBF);
            tv_benjin.setBackgroundResource(R.color.greenAD);
        }
        //贷款月数(默认值)
        monthCount = PieChartFragment.GJJ_MONTHCOUNT;
        seekBar_big.setProgress(monthCount / 12);
        seekBar_normal.setProgress(monthCount / 12);

        //月利率(默认值)
        if (monthCount <= 60) {
            monthlyRate = PieChartFragment.GJJ_RATE_1_5;
        } else {
            monthlyRate = PieChartFragment.GJJ_RATE_5;
        }
        tv_rate.setText(df_rate.format(monthlyRate * 12 * 100) + "%");
    }

    private void initPieChart() {
        pie_chart = (PieChart) mView.findViewById(R.id.pie_chart);
        pie_chart.setUsePercentValues(false);//使用百分比
        pie_chart.setDescription("");
        pie_chart.setExtraOffsets(5, 10, 5, 5);

        pie_chart.setDragDecelerationFrictionCoef(0.95f);//设置滑动惯性

        pie_chart.setDrawHoleEnabled(true);//是否绘制中间空白区
        pie_chart.setHoleColorTransparent(true);//设置中间空白区透明

        pie_chart.setTransparentCircleColor(Color.BLACK);//设置中间空白区与周边扇形图之间的间隙环
        pie_chart.setTransparentCircleAlpha(110);//间隙环透明度

        pie_chart.setHoleRadius(40f);//中间空白区半径
        pie_chart.setTransparentCircleRadius(40f);//间隙环半径

        pie_chart.setDrawCenterText(true);//设置是否显示中间空白区文字

        pie_chart.setRotationAngle(0);//起始角度
        // enable rotation of the chart by touch
        pie_chart.setRotationEnabled(false);//是否可滑动旋转
        pie_chart.setHighlightPerTapEnabled(true);//是否可点击扇形

        // add a selection listener
        pie_chart.setOnChartValueSelectedListener(this);

        //setData();
        calculate();

        // pie_chart.spin(2000, 0, 360);

        pie_chart.getLegend().setEnabled(false);
    }

    private void setData() {
        pie_chart.setCenterTextSize(13f);
        if (null != monthlyPrincipalInterests && monthlyPrincipalInterests.length > 1) {
            if (type == 1) {
                //等额本金
                pie_chart.setCenterText("首月月供 " + df.format(monthlyPrincipalInterests[0]) + "元");
            } else {
                //等额本息(默认)
                pie_chart.setCenterText("参考月供 " + df.format(monthlyPrincipalInterests[0]) + "元");
            }
        }

        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        yVals1.add(new Entry((float) interestAmount, 0));
        yVals1.add(new Entry((float) loanAmount, 1));

        ArrayList<String> xVals = new ArrayList<String>();
        xVals.add("利息");
        xVals.add("本金");

        PieDataSet dataSet = new PieDataSet(yVals1, "Election Results");
        dataSet.setSliceSpace(2f);//两扇形见空隙大小
        dataSet.setSelectionShift(5f);//点击扇形向外位移大小

        ArrayList<Integer> colors = new ArrayList<Integer>();

        colors.add(Color.parseColor("#cce198"));//浅绿
        colors.add(Color.parseColor("#22b26d"));//绿色

        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);

        //是否显示百分比
        dataSet.setDrawValues(true);

        PieData data = new PieData(xVals, dataSet);
        data.setValueFormatter(new WanFormatter("万元"));
        data.setValueTextSize(12f);
        data.setValueTextColor(Color.BLACK);
        pie_chart.setData(data);

        // undo all highlights
        pie_chart.highlightValues(null);

        //是否显示扇形文本
        pie_chart.setDrawSliceText(true);

        pie_chart.invalidate();

        pie_chart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
    }

    private void calculate() {
        //贷款月数
        monthCount = seekBar_normal.getProgress() * 12;
        //月均贷款额
        monthlyLoan = loanAmount / monthCount;
        //月还本息数组
        monthlyPrincipalInterests = new double[monthCount];

        if (type == 1) {
            //等额本金
            calculateBenJin();
        } else {
            //等额本息(默认)
            calculateBenXi();
        }
        setData();

        tv_totalprice.setText(df.format(repaymentAmount / 10000) + "万");
        scrollview.smoothScrollTo(0, 0);
    }

    /**
     * 计算“等额本息”
     */
    private void calculateBenXi() {
        repaymentAmount = 0;
        interestAmount = 0;

        for (int i = 0; i < monthCount; i++) {
            // 等额本息
            //月还本息 = 贷款总额 * 月利率 * （1 + 月利率） ^ 贷款月数 / （（1 + 月利率） ^ （贷款月数） - 1）
            monthlyPrincipalInterests[i] = loanAmount * monthlyRate * Math.pow(1 + monthlyRate, monthCount)
                    / (Math.pow(1 + monthlyRate, monthCount) - 1);
        }
        //还款总额 = 月本息 * 贷款月数
        repaymentAmount = monthlyPrincipalInterests[0] * monthCount;
        //利息总额
        interestAmount = repaymentAmount - loanAmount;
    }

    /**
     * 计算“等额本金”
     */
    private void calculateBenJin() {
        repaymentAmount = 0;
        interestAmount = 0;

        for (int i = 0; i < monthCount; i++) {
            // 等额本金
            //月还本息 = （贷款总额 - 月均贷款额 * 贷款月数） * 月利率 + 月均贷款额
            monthlyPrincipalInterests[i] = (loanAmount - monthlyLoan * i) * monthlyRate + monthlyLoan;
            //还款总额 = 月本息之和
            repaymentAmount += monthlyPrincipalInterests[i];
        }
        //利息总额
        interestAmount = repaymentAmount - loanAmount;
    }

    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {

        if (e == null)
            return;
        Log.i("VAL SELECTED",
                "Value: " + e.getVal() + ", xIndex: " + e.getXIndex()
                        + ", DataSet index: " + dataSetIndex);
    }

    @Override
    public void onNothingSelected() {
        Log.i("PieChart", "nothing selected");
    }

    private void setRateText(String rateValue) {
        if (StringUtils.canParseDouble(rateValue)) {
            double monthRate = Double.parseDouble(rateValue) / (100 * 12);
            if (seekBar_normal.getProgress() <= 5) {
                PieChartFragment.GJJ_RATE_1_5 = monthRate;
            } else {
                PieChartFragment.GJJ_RATE_5 = monthRate;
            }
            monthlyRate = monthRate;
            tv_rate.setText(df_rate.format(monthRate * 12 * 100) + "%");
            calculate();
        }
    }

    public void resetValues() {
        try {
            initDefaultValues(defaultLoanAmount, 0);
            calculate();
        } catch (Exception e) {

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null != data) {
            String rateValue = data.getStringExtra("rateValue");
            setRateText(rateValue);
        }
    }
}
